import base64
import logging
import json
import uuid
from common import PublicValidate, Response, UserInfo, UserInfoDynamoDB, ValidateService, DecimalEncoder
from configuration import is_running_on_aws_lambda

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not is_running_on_aws_lambda():
    handler = logging.StreamHandler()
    # format the log
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    
def lambda_handler(event: dict, context):
    logger.info("Received event: " + json.dumps(event, indent=2, cls=DecimalEncoder))
    query = event.get('queryStringParameters', {})
    method = event.get('requestContext', {}).get('http', {}).get('method', 'GET')
    body = event.get('body', {})
    try:
        body = json.loads(body)
    except:
        pass
    
    method_handler = {
        'GET': handle_get,
        'POST': handle_post,
        'PUT': handle_put,
        'DELETE': handle_delete,
    }
    
    return method_handler[method](query, event, body)

def handle_get(query: dict, event: dict, body: dict):
    if query.get('register_code', None):
        return Response.build_success_response({
            'code': ValidateService.Guid
        })
        
    public_validate = PublicValidate(event)
    is_valid, response = public_validate.validate()
    if not is_valid:
        return Response.build_error_response(response, 403)
    
    return Response.build_success_response(response.to_dict())

def handle_post(query: dict, event: dict, body: dict):
    headers = event.get('headers', {})
    api_key = extract_api_key(headers)
    logger.info(f"API key extracted: {api_key[:4]}...{api_key[-4:]}" if api_key else "No API key found")
    if not api_key:
        logger.error("Unauthorized, apikey is required")
        return Response.build_error_response("Unauthorized, apikey is required", 403)
    
    # 统一ApiKey格式，base64编码的：user_id$$accessToken$$platform$$platform_user_id
    validate_service = ValidateService(api_key)
    is_valid, response = validate_service.validate()
    if not is_valid:
        logger.error(f"Unauthorized, apikey is invalid: {api_key}")
        return Response.build_error_response(response, 403)
    user_info: UserInfo = response
    
    if not user_info.Id:
        user_info.Id = str(uuid.uuid4())
    
    user_info_dynamodb = UserInfoDynamoDB(user_info)
    is_success, data = user_info_dynamodb.save_change()
    if not is_success:
        logger.error(f"Save user info failed: {data}")
        return Response.build_error_response(data, 500)
    
    return Response.build_success_response(data)
    
def handle_put(query: dict, headers: dict, body: dict):
    pass

def handle_delete(query: dict, headers: dict, body: dict):
    pass

def extract_api_key(headers):
    """从请求头中提取API Key"""
    api_key = None
    for key in ['apikey', 'ApiKey', 'Apikey', 'Api-Key', 'api-key']:
        if key in headers:
            api_key = headers[key]
            break
    logger.info(f"API key extracted: {api_key[:4]}...{api_key[-4:]}" if api_key else "No API key found")
    return api_key
    